package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Classinfo;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.ClassinfoQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IClassinfoService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/classinfo")
public class ClassinfoController {

    //  获取容器中IClassinfoService的实现类对象，并注入Bean
    @Autowired
    private IClassinfoService classinfoService;

    @Autowired
    private IEmployeeService employeeService;

    //  查询方法
    @RequestMapping("/list")
    @RequiredPermission(name = "班级列表", expression = "classinfo:list")
    public String list(Model model, @ModelAttribute("qo") ClassinfoQueryObject qo) {
        //  调用Service层的query方法
        PageInfo<Classinfo> pageInfo = classinfoService.query(qo);
        //  将获取到的数据设置到模型中
        model.addAttribute("pageResult", pageInfo);

        List<Employee> employees = employeeService.selectAll();
        model.addAttribute("employees", employees);

        //  找视图/WEB-INF/views/classinfo/list.ftl
        return "classinfo/list";
    }

    //  删除方法
    @RequestMapping("/delete")
    @ResponseBody
    @RequiredPermission(name = "班级删除", expression = "classinfo:delete")
    public JsonResult delete(Long id) {
        try {
            //  判断id是否存在
            if (id != null) {
                //  调用Service层的deleteById方法
                classinfoService.deleteById(id);
            }
            return new JsonResult(true, "删除成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new JsonResult(false, "删除失败");
        }
    }

    //  新增或修改页面方法
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "班级保存或更新", expression = "classinfo:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Classinfo classinfo) {
        try {
            //  判断id是否存在
            if (classinfo.getId() != null) {
                //  若存在，调用Service层的updateById方法
                classinfoService.updateById(classinfo);
            } else {
                //  若不存在，调用Service层的insert方法
                classinfoService.insert(classinfo);
            }
            return new JsonResult(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败");
        }
    }
}
